<?php

namespace App\Http\Controllers;

use App\Url;
use Illuminate\Http\Request;

class UrlController extends Controller
{
    public function getAll() {
        $url=Url::where('rank',0)->orderBy('listRank','asc')->get();
        return response()->json($url);
    }

    public function getCompanyAll( $company ) {
        $urls=Url::orderBy('listRank','asc')->get();
        return response()->json($urls);
    }

    public function getChildren($id) {
        $url=Url::where('pid',$id)->get();
        return response()->json($url);
    }
    public function one($id) {
        $one=Url::find($id);
        return response()->json($one);
    }
    public function add(Request $request) {

        $add['name']=$request->input('name');
        $add['url']=$request->input('url');
        $add['rank']=$request->input('rank');
        $add['parent']=0;
        $add['listRank']=$request->input('listRank');
        $add['pid']=$request->input('pid');
        if($add['pid'] > 0 ){
            $add['rank']=1;
            Url::find($add['pid'])->update(['url'=>'parent']);
        }
        $add['ico']=$request->input('ico');
        $add['state']=$request->input('state');
        $hasName=Url::where('name',$add['name'])->count();
        if($hasName > 0){
            return response()->json('导航名已存在，添加失败');
        }else{
            Url::create($add);
            return response()->json('添加成功');
        }

    }
    public function del ($id) {
        $url=Url::find($id);
        if($url){
            $url->delete();
            return response()->json('删除成功');
        }
        return response()->json('目标不存在');

    }
    public function update($id, Request $request) {
        $pUrlId=Url::where('id',$id)->value('pid');


        $add=$request->only(['name','url','rank','listRank','pid','ico','state']);

        Url::find($id)->update($add);
        if ($pUrlId > 0){
            $pNum= Url::where('pid',$pUrlId)->count();
            if ($pNum == 0){
                Url::Where('id',$pUrlId)->update(['parent'=>0]);
            }
        }
        if($add['pid'] > 0){
                Url::Where('id',$add['pid'] )->update(['parent'=>1]);
            Url::Where('id',$id)->update(['rank'=>1]);
        }elseif($add['pid'] == 0){
            Url::Where('id',$id)->update(['rank'=>0]);
        }
        return response()->json('修改成功');
    }

}
